<template>
	<view>
		<view class="from">
			<view class="sd_box_list">
				<view class="ft_ft_box">
					<view class="left_icon">
						<image src="@/static/image/user.png" mode="" width="28rpx" height="30rpx"></image>
					</view>
					<view class="ft_ft_info">
						<view class="">
							姓名
						</view>
					</view>
				</view>
				<view class="rt_ip">
					<input type="text" placeholder="请输入姓名" @input="onChangeField1($event)"  />
				</view>
			</view>
			<van-divider />

			<view class="sd_box_list">
				<view class="ft_ft_box">
					<view class="left_icon">
						<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/dh_icon.png" mode="" width="28rpx" height="30rpx"></image>
					</view>
					<view class="ft_ft_info">
						<view class="">
							电话
						</view>
					</view>
				</view>
				<view class="rt_ip">
					<input type="number" placeholder="请输入电话" @input="onChangeField2($event)"   />
				</view>
			</view>
			<van-divider />

			<!-- 身份证正面照片上传区域 -->
			<view class="upload-container">
				<van-field clearable label="身份证正面" center use-button-slot :border="false">
					<view slot="button">
						<van-uploader :file-list="fileList" @after-read="afterRead">
							<view class="text-center pl-[30rpx] bg-[#fff]">
								<van-image radius="20rpx" fit="cover" width="100rpx" height="100rpx" :src="headImg" />
								<van-icon name="arrow" size="16" class="ml--20rpx-" />
							</view>
						</van-uploader>
					</view>
				</van-field>
			</view>

			<!-- 身份证反面照片上传区域 -->
			<view class="upload-container">
				<van-field clearable label="身份证反面" center use-button-slot :border="false">
					<view slot="button">
						<van-uploader :file-list="fileList" @after-read="afterRead1">
							<view class="text-center pl-[30rpx] bg-[#fff]">
								<van-image radius="20rpx" fit="cover" width="100rpx" height="100rpx" :src="headImg1" />
								<van-icon name="arrow" size="16" class="ml--20rpx-" />
							</view>
						</van-uploader>
					</view>
				</van-field>
			</view>

			<!-- 学生证照片上传区域 -->
			<view class="upload-container">
				<van-field clearable label="证件照片" center use-button-slot :border="false">
					<view slot="button">
						<van-uploader :file-list="fileList" @after-read="afterRead2">
							<view class="text-center pl-[30rpx] bg-[#fff]">
								<van-image radius="20rpx" fit="cover" width="100rpx" height="100rpx" :src="headImg2" />
								<van-icon name="arrow" size="16" class="ml--20rpx-" />
							</view>
						</van-uploader>
					</view>
				</van-field>
			</view>

			<view class="sd_box_list">
				<view class="ft_ft_box">
					<view class="left_icon">
						<image src="@/static/image/xy.png" mode=""></image>
					</view>
					<view class="ft_ft_info">
						<view>
							电子协议
						</view>
					</view>
				</view>
				<view class="dianzixy rt_tit">
					<van-checkbox :value="dztogs" shape="square" @change="togclick"></van-checkbox>
					<view class="agreement-text" @click="showAgreementModal">查看并同意协议</view>
				</view>
			</view>
			<view class="sd_box_list">
				<view class="ft_ft_box">
					<view class="left_icon">
						<image src="@/static/image/grenn_user.png" mode=""></image>
					</view>
					<view class="ft_ft_info">
						<view class="">
							加急审核
						</view>
					</view>
				</view>
				<view class="rt_tit" @click="linkAdmin">
					联系校区管理员
				</view>
			</view>

		</view>
		<view class="botton_flex" v-if="status">
			<button style="background-color: #3c91ff; color: white; border-radius: 50rpx; margin-top: 80rpx;width: 90%;"
				@click="onClickButton">提交申请</button>
		</view>
	</view>

	<!-- 协议弹框 -->
	<view style="position: absolute;
    top: 0px;
    background-color: #fff;z-index: 999;" v-if="agreementModalVisible" title="电子协议" width="90%">
		<view class="agreement-content">
			<text class="agreement-title">用户服务协议</text>
			<view class="agreement-body">
				<text class="agreement-section-title">第一章 总则</text>
				<text class="agreement-paragraph">1.1 本协议是用户与平台之间关于使用本服务的法律协议。</text>
				<text class="agreement-paragraph">1.2 用户在使用本服务前，应仔细阅读本协议所有条款。</text>

				<text class="agreement-section-title">第二章 服务内容</text>
				<text class="agreement-paragraph">2.1 平台为用户提供校园服务，包括但不限于信息发布、身份认证等。</text>
				<text class="agreement-paragraph">2.2 用户需如实填写个人信息，确保信息真实有效。</text>

				<text class="agreement-section-title">第三章 用户权利与义务</text>
				<text class="agreement-paragraph">3.1 用户有权使用平台提供的各项服务，但需遵守本协议及平台规则。</text>
				<text class="agreement-paragraph">3.2 用户保证提交的所有信息真实合法，不侵犯他人权益。</text>

				<text class="agreement-section-title">第四章 隐私保护</text>
				<text class="agreement-paragraph">4.1 平台保护用户隐私，未经用户同意不向第三方披露个人信息。</text>
				<text class="agreement-paragraph">4.2 平台有权在必要情况下使用用户信息进行服务优化。</text>

				<text class="agreement-section-title">第五章 协议变更</text>
				<text class="agreement-paragraph">5.1 平台有权根据需要变更本协议，变更前将通过适当方式通知用户。</text>
				<text class="agreement-paragraph">5.2 用户继续使用服务即视为同意协议变更内容。</text>
			</view>
			<view class="agreement-footer">
				<text class="agreement-confirm" @click="confirmAgreement">我已阅读并同意上述协议</text>
			</view>
		</view>
	</view>

	<!-- 未勾选协议提示弹框 -->
	<van-dialog v-model:show="needAgreementModalVisible" title="提示" width="60%"
		@confirm="needAgreementModalVisible = false">
		<text>请先阅读并同意电子协议后再提交申请</text>
	</van-dialog>

	<van-dialog use-slot :title="'电话'+adminInfo.mobile" :show="!togs" @confirm="togs = true">
		<view class="" style="display: flex; justify-content: center;">
			<image style="width: 200rpx; height: 200rpx;" :src="adminInfo.image_text" mode=""></image>
		</view>
	</van-dialog>

</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import uploadRequest from '@/utils/uploadRequest.js'
	import {
		postUserInfo
	} from '@/api/api.js'
	import {
		shenQingJieDan,
		jieDanShenQingZhuangTai,
		getSchoolMengerPhone,		getSchoolIdBy
	} from "@/api/xiaoquan.js"
	const headImg1 = ref('https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png');
	const headImg2 = ref('https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png');
	const headImg = ref('https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png');
	const fileList = ref([]);
	const loading = ref(false);
	const schoolId = ref('');
	// 协议弹框状态
	const agreementModalVisible = ref(false);
	// 未勾选协议提示弹框状态
	const needAgreementModalVisible = ref(false);
	// 协议是否已确认
	const agreementConfirmed = ref(false);

	// 图片上传处理
	const afterRead = async (res) => {
		loading.value = true;
		try {
			await uploadRequest({
				filePath: res.detail.file.tempFilePath,
				url: '/api/front/hitch/passengerManager/uploadAvatar',
				formData: {
					multipart: res.detail.file
				},
				header: {
					"Authori-zation": uni.getStorageSync('token'),
					"Content-Type": "multipart/form-data"
				},
			}).then(result => {
				if (result.code == 200) {
					headImg.value = result.data;
					uni.showToast({
						title: '图片上传成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: result.message || '上传失败',
						icon: 'none'
					});
				}
			});
		} catch (error) {
			console.log(error);
			uni.showToast({
				title: '上传出错，请重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}

	// 图片上传处理
	const afterRead1 = async (res) => {
		loading.value = true;
		try {
			await uploadRequest({
				filePath: res.detail.file.tempFilePath,
				url: '/api/front/hitch/passengerManager/uploadAvatar',
				formData: {
					multipart: res.detail.file
				},
				header: {
					"Authori-zation": uni.getStorageSync('token'),
					"Content-Type": "multipart/form-data"
				},
			}).then(result => {
				if (result.code == 200) {
					headImg1.value = result.data;
					uni.showToast({
						title: '图片上传成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: result.message || '上传失败',
						icon: 'none'
					});
				}
			});
		} catch (error) {
			console.log(error);
			uni.showToast({
				title: '上传出错，请重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}

	// 图片上传处理
	const afterRead2 = async (res) => {
		loading.value = true;
		try {
			await uploadRequest({
				filePath: res.detail.file.tempFilePath,
				url: '/api/front/hitch/passengerManager/uploadAvatar',
				formData: {
					multipart: res.detail.file
				},
				header: {
					"Authori-zation": uni.getStorageSync('token'),
					"Content-Type": "multipart/form-data"
				},
			}).then(result => {
				if (result.code == 200) {
					headImg2.value = result.data;
					uni.showToast({
						title: '图片上传成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: result.message || '上传失败',
						icon: 'none'
					});
				}
			});
		} catch (error) {
			console.log(error);
			uni.showToast({
				title: '上传出错，请重试',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}

	// 表单数据模型
	const postData = ref({
		fullName: '',
		phone: '',
		idCardFront: 'https://aw2025ht.kangye.xyz/api/profile/upload/tou.jpg',
		idCardBack: '',
		studentCard: '',
	})
	const login_data = ref([])
	const userId = ref("")
	const adminInfo = ref({})
	const togs = ref(true)
	const dztogs = ref(false)
	const status = ref(true)
	const applicationStatus = ref(-1)
	const filedBorder = ref(false)

	// 上传文件列表
	const idCardFrontFileList = ref([])
	const idCardBackFileList = ref([])
	const studentCardFileList = ref([])

	// 状态码映射
	const statusTextMap = {
		'-1': '未申请',
		'0': '待审核',
		'1': '已通过',
		'2': '已拒绝'
	}


	// 页面显示时加载本地数据
	onShow(async() => {
		// 每次查询一下用户学校id，并保存，如果没有则先选择学校
		let res = await getSchoolIdBy();
		schoolId.value = res.data;
		uni.setStorageSync('school_id', schoolId.value)
		console.log(res, 333333333)
		if (!schoolId.value) {
		
			wx.showToast({
				title: '请先选择学校',
				icon: 'none',
				duration: 1000 // 提示停留2秒
			});
		
			// 延迟2秒后跳转到登录页
			setTimeout(() => {
				uni.navigateTo({
					url: `/package/pages/selectSchool/selectSchool`
				});
			}, 1000);
		
			return;
		}
		// login_data.value = uni.getStorageSync('login_data')
		// postData.value = {
			
		// 	idCardFront: login_data.value.idCardFront ||
		// 		'',
		// 	idCardBack: login_data.value.idCardBack || '',
		// 	studentCard: login_data.value.studentCard || '',
		// }
		checkApplicationStatus()
	})

	/*查询申请状态*/
	const checkApplicationStatus = async () => {
		try {
			const res = await jieDanShenQingZhuangTai()
			if (res.code === 200) {
				console.log(res.data, 111111111)
				applicationStatus.value = res.data

				if (applicationStatus.value !== -1) {
					const statusText = statusTextMap[applicationStatus.value + ''] || '未知状态'
					uni.showToast({
						title: `${statusText}`,
						icon: 'none',
						duration: 2000
					})
					setTimeout(() => uni.navigateBack(), 2000)
				}
			}
		} catch (error) {
			console.error('查询申请状态出错:', error)
			uni.showToast({
				title: '网络错误，请稍后再试',
				icon: 'none'
			})
		}
	}

	/*联系管理员*/
	const linkAdmin = async () => {
		getSchoolMengerPhone().then((apiRes) => {
			if (apiRes && apiRes.data) {
				uni.showModal({
					title: '墙墙の电话',
					content: apiRes.data,
					confirmText: '复制',
					cancelText: '取消',
					success: (modalRes) => {
						if (modalRes.confirm) {
							if (typeof apiRes.data === 'string' && apiRes.data.trim() !== '') {
								uni.setClipboardData({
									data: apiRes.data,
									success: () => {
										uni.showToast({
											title: '电话已复制',
											icon: 'success'
										});
									},
									fail: (err) => {
										console.error('复制失败', err);
										uni.showToast({
											title: '复制失败，请稍后重试',
											icon: 'none'
										});
									}
								});
							} else {
								uni.showToast({
									title: '电话数据格式错误，无法复制',
									icon: 'none'
								});
							}
						}
					}
				});
			} else {
				uni.showToast({
					title: '获取客服微信失败',
					icon: 'none'
				});
			}
		}).catch((err) => {
			console.error('获取客服微信请求失败', err);
			uni.showToast({
				title: '网络请求失败，请稍后重试',
				icon: 'none'
			});
		});
	}

	/*身份证正面图片上传处理*/
	const handleIdCardFrontUpload = async (res) => {
		await handleImageUpload(res, 'idCardFront', idCardFrontFileList)
	}

	/*身份证反面图片上传处理*/
	const handleIdCardBackUpload = async (res) => {
		await handleImageUpload(res, 'idCardBack', idCardBackFileList)
	}

	/*学生证图片上传处理*/
	const handleStudentCardUpload = async (res) => {
		await handleImageUpload(res, 'studentCard', studentCardFileList)
	}

	/*统一图片上传处理逻辑*/
	const handleImageUpload = async (res, fieldName, fileListRef) => {
		try {
			const file = res.detail.file
			if (!file) return

			const maxSize = 2 * 1024 * 1024
			if (file.size > maxSize) {
				uni.showToast({
					title: '图片大小不能超过2MB',
					icon: 'none'
				})
				return
			}

			const result = await uploadRequest({
				filePath: file.tempFilePath,
				url: '/api/front/hitch/passengerManager/uploadAvatar',
				formData: {
					multipart: file
				},
				header: {
					"Authorization": uni.getStorageSync('token'),
					"Content-Type": "multipart/form-data"
				},
			})

			if (result.code === 200) {
				postData.value[fieldName] = result.data
				fileListRef.value = [{
					url: result.data
				}]
				uni.showToast({
					title: '上传成功',
					icon: 'success'
				})
			} else {
				uni.showToast({
					title: result.msg || '上传失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('图片上传出错:', error)
			uni.showToast({
				title: '上传失败，请稍后再试',
				icon: 'none'
			})
		}
	}

	const togclick = (e) => {
		dztogs.value = e.detail;
		console.log('电子协议勾选状态:', dztogs.value)
	}

	/*点击协议显示弹框*/
	const showAgreementModal = () => {
		agreementModalVisible.value = true;
	}

	/*确认协议*/
	const confirmAgreement = () => {
		agreementConfirmed.value = true;
		dztogs.value = true;
		agreementModalVisible.value = false;
	}

	/*表单字段变更处理*/
	const onChangeField1 = (ev) => {
		console.log(ev.detail.value)
		postData.value.fullName = ev.detail.value
	}


	/*表单字段变更处理*/
	const onChangeField2 = (ev) => {
		console.log(ev.detail.value)
		postData.value.phone = ev.detail.value
	}



	/*提交申请处理*/
	const onClickButton = () => {
		// 表单验证
		postData.value.idCardFront = headImg.value;
		postData.value.idCardBack = headImg1.value;
		postData.value.studentCard = headImg2.value;
		console.log(postData.value)
		console.log(postData.value,123321)
		const phoneRegex = /1\d{10}$/;
		if (!postData.value.fullName) {
			uni.showToast({
				title: '请输入姓名',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		if (!phoneRegex.test(postData.value.phone)) {
			uni.showToast({
				title: '请输入有效的手机号',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		
		if (!postData.value.idCardFront || headImg.value ==
			'https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png') {
			uni.showToast({
				title: '请上传身份证正面照片',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		if (!postData.value.idCardBack || headImg1.value ==
			'https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png') {
			uni.showToast({
				title: '请上传身份证反面照片',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		if (!postData.value.studentCard || headImg2.value ==
			'https://paole.hebeixiaoyu.cn/run/profile/upload/loukongxiangji.png') {
			uni.showToast({
				title: '请上传学生证照片',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		if (!dztogs.value) {
			
			uni.showToast({
				title: '请先阅读并同意协议',
				duration: 1000,
				icon: 'none'
			});
			return
		}

		// 构建申请对象
		const application = {
			userId: userId.value,
			fullName: postData.value.fullName,
			phone: postData.value.phone,
			idCardFront: postData.value.idCardFront,
			idCardBack: postData.value.idCardBack,
			studentCard: postData.value.studentCard,
			applicationTime: new Date().toISOString(),
			status: 0
		};

		// 提交申请并更新本地存储
		shenQingJieDan(application).then(res => {
			if (res.code === 200) {
				// if (postData.value.idCardFront) login_data.value.idCardFront = postData.value.idCardFront;
				// if (postData.value.idCardBack) login_data.value.idCardBack = postData.value.idCardBack;
				// if (postData.value.studentCard) login_data.value.studentCard = postData.value.studentCard;
				// if (postData.value.fullName) login_data.value.fullName = postData.value.fullName;
				// if (postData.value.phone) login_data.value.phone = postData.value.phone;

				// uni.setStorageSync('login_data', login_data.value);
				uni.showToast({
					title: '提交申请成功',
					duration: 1000,
					icon: 'success'
				});

				setTimeout(() => {
					uni.switchTab({
						url: '/pages/mine/mine'
					});
				}, 1000);
			}
		}).catch(er => console.log(er))
	}
</script>

<style scoped>
	.from {
		margin: 30rpx 20rpx;
		border-radius: 15rpx;
		padding: 10rpx;
		background-color: #fff;
	}

	.sd_box_list {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
	}

	.ft_ft_box {
		display: flex;
		align-items: center;
		font-size: 32rpx;
	}

	.ft_ft_info {
		margin-left: 20rpx;
	}

	.rt_ip {
		width: 220rpx;
		color: black;
	}

	.rt_tit {
		color: #3c91ff;
	}

	.dianzixy {
		display: flex;
		font-size: 32rpx;
		align-items: center;
	}

	::v-deep .van-checkbox__icon {
		border-radius: 15rpx;
	}

	input::placeholder {
		color: #999;
	}

	.left_icon {
		width: 28rpx;
		height: 30rpx;
	}

	.botton_flex {
		display: flex;
		justify-content: center;
		padding: 30rpx 0;
	}

	/* 新上传组件样式 */
	.upload-container {
		background-color: #fff;
		border-radius: 15rpx;
		padding: 10rpx;
		margin: 10rpx 0;
	}

	::v-deep .van-cell {
		padding: 30rpx 16rpx !important;
		border: 0rpx;
	}

	::v-deep .van-field__label {
		color: #111111;
		font-size: 36rpx;
		font-weight: 500;
	}

	.text-center {
		display: flex;
		align-items: center;
	}

	/* 协议弹框样式 */
	.agreement-content {
		padding: 30rpx;
	}

	.agreement-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
		text-align: center;
		display: block;
		color: #333;
	}

	.agreement-body {
		font-size: 28rpx;
		line-height: 1.8;
		color: #666;
		margin-bottom: 30rpx;
	}

	.agreement-section-title {
		font-weight: bold;
		margin: 20rpx 0 10rpx;
		display: block;
		color: #333;
	}

	.agreement-paragraph {
		margin-bottom: 15rpx;
		text-align: justify;
	}

	.agreement-footer {
		text-align: center;
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #eee;
	}

	.agreement-confirm {
		color: #3c91ff;
		text-decoration: underline;
		cursor: pointer;
	}

	.agreement-text {
		color: #3c91ff;
		text-decoration: underline;
		margin-left: 10rpx;
		cursor: pointer;
	}
</style>